package com.zj.osm.view.project.projectdetail.fragment;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

import com.blankj.utilcode.util.ToastUtils;
import com.zj.osm.App;
import com.zj.osm.R;
import com.zj.osm.adapter.PoleAdapter2;
import com.zj.osm.bean.PoleAdapterBean;
import com.zj.osm.bean.PoleBean;
import com.zj.osm.entity.db.EquipmentDao;
import com.zj.osm.entity.db.LineDao;
import com.zj.osm.entity.db.PointDao;
import com.zj.osm.entity.db.ProjectDao;
import com.zj.osm.entity.greendao.Equipment;
import com.zj.osm.entity.greendao.Line;
import com.zj.osm.entity.greendao.Point;
import com.zj.osm.entity.greendao.Project;
import com.zj.osm.utils.CoordinateTool;
import com.zj.osm.utils.ExcelUtil;
import com.zj.osm.utils.ExportUnit;
import com.zj.osm.utils.GaussKrugerProjection;
import com.zj.osm.utils.view_utils.PopupMenuPole;
import com.zj.osm.view.project.projectdetail.ProjectDetailActivity;
import com.zj.utils.utils.ShareUtils;
import com.zj.utils.utils.ThreadManager;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.annotations.NonNull;

import static com.zj.utils.utils.ThreadManager.getThreadPool;

/**
 * 勘察信息
 * 本地項目詳情中的fragment
 */
public class PoleFragment extends Fragment implements View.OnClickListener {

    private ImageButton detailsBtnBack;
    private TextView detailsTvOne;
    private TextView detailsTvTwo;
    private Button detailsBtnJc;
    private Button detailsBtnKcxx;
    private Button detailsBtnWlqd;
    private Button detailsBtnGdfa;
    private ProgressDialog mProgressDialog;
    private List<PoleBean> bomBeanresult = new ArrayList<>();

    /**
     * 塔杆明细
     */

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_pole, container, false);
        initView(view);
        return view;
    }


    List<PoleAdapterBean> poleFragmentBeansData = new ArrayList<>();
    com.zj.osm.entity.greendao.Project Project;
    List<Point> pointsList;
    List<Line> line;
    private void initView(View view) {
        poleFragmentBeansData.clear();
        //TODO Whether是否为地形点 1代表是地形点吧但是这里如果是地形拐点就需要搞定为0
        pointsList= App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.ProjectId.eq(ProjectDetailActivity.PROJECT_DETAILS_ID)).build().list();
        Project=App.getInstances().getDaoSession().getProjectDao().queryBuilder().where(ProjectDao.Properties.Id.eq(ProjectDetailActivity.PROJECT_DETAILS_ID)).unique();
        line= App.getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Item_id.eq(ProjectDetailActivity.PROJECT_DETAILS_ID)).build().list();
        ListView pole_listView = view.findViewById(R.id.pole_listView);
        List<String> cross = new ArrayList<String>();
        cross.add("DLGD");
        cross.add("DXD");
        cross.add("LJD");
        cross.add("GDYX");
        cross.add("LJD");
        for (int i = 0; i < pointsList.size(); i++) {
            Log.e("point=", pointsList.get(0).toString1());
            PoleBean pointPoleBean = new PoleBean();
            boolean isContain = false;
            if (cross.size() > 0 && pointsList.get(i).getMark() != null)
                for (String s : cross) {
                    if (pointsList.get(i).getMark().contains(s)) {
                        isContain = true;
                    }
                }
            if (!isContain) {
                GaussKrugerProjection.Tuple tuple= get2000XY(pointsList.get(i).getLatitude().toString(),pointsList.get(i).getLongitude().toString());
                pointPoleBean.setEquipCode(pointsList.get(i).getMark());
                /*pointPoleBean.setEquipStartX(tuple.getB() + "");
                pointPoleBean.setEquipStartY(tuple.getL() + "");
                pointPoleBean.setEquipEndX("");
                pointPoleBean.setEquipEndY("");*/
                pointPoleBean.setEquipEndLat(pointsList.get(i).getLatitude().toString());
                pointPoleBean.setEquipEndLong(pointsList.get(i).getLongitude().toString());
                pointPoleBean.setEquipEndNote(pointsList.get(i).getNote()==null?"":pointsList.get(i).getNote());
                PoleAdapterBean poleFragmentBean = new PoleAdapterBean();
                poleFragmentBean.setTypeName("" + pointsList.get(i).getName() + pointsList.get(i).getMark());
                poleFragmentBean.setStatu(pointsList.get(i).getState());
                poleFragmentBean.setPoint(true);
                pointPoleBean.setEquipEndHeight(pointsList.get(i).getHigh()==null?"":pointsList.get(i).getHigh());
                List<Equipment> allEm = new ArrayList<>();
                List<Equipment> equipmentData = App.getInstances().getDaoSession().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.PointId.eq(pointsList.get(i).getId()), EquipmentDao.Properties.Qubie.eq(0)).build().list();
                List<Equipment> getEquipmentList = App.getInstances().getDaoSession().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.PointId.eq(pointsList.get(i).getId()), EquipmentDao.Properties.Qubie.eq(2)).build().list();
                poleFragmentBean.setPointOrLine(pointsList.get(i));
                if (equipmentData.size() > 0) {
                    allEm.addAll(equipmentData);
                    pointPoleBean.setEquipCategory(equipmentData.get(0).getName());
                    pointPoleBean.setEquipType(equipmentData.get(0).getThreeName());
                    pointPoleBean.setEquip(0);
                }
                if (getEquipmentList.size() > 0) {
                    allEm.addAll(getEquipmentList);

                }
                poleFragmentBean.setEquipmentList(allEm);
                poleFragmentBeansData.add(poleFragmentBean);
                bomBeanresult.add(pointPoleBean);
            }
        }
        /*for (int i = 0; i < line.size(); i++) {
            PoleBean pointPoleBean = new PoleBean();
            GaussKrugerProjection.Tuple tuple= get2000XY(line.get(i).getLatA(),line.get(i).getLonA());
            GaussKrugerProjection.Tuple tupleB= get2000XY(line.get(i).getLatB(),line.get(i).getLonB());
            pointPoleBean.setEquipCode(line.get(i).getName());
            *//*pointPoleBean.setEquipStartX(tuple.getB()+ "");
            pointPoleBean.setEquipStartY(tuple.getL() + "");
            pointPoleBean.setEquipEndX(tupleB.getB()+ "");
            pointPoleBean.setEquipEndY(tupleB.getL() + "");*//*
            pointPoleBean.setEquipType(line.get(0).getTypes());
            pointPoleBean.setEquipCategory(line.get(0).getType());
            PoleAdapterBean poleFragmentBean = new PoleAdapterBean();
            poleFragmentBean.setTypeName(line.get(i).getName());
            poleFragmentBean.setStatu(line.get(i).getState());
            poleFragmentBean.setPoint(false);
            Equipment equipment = new Equipment();
            equipment.setName(line.get(i).getTypes());
            List<Equipment> equipment1 = new ArrayList<>();
            equipment1.add(equipment);
            poleFragmentBean.setEquipmentList(equipment1);
            poleFragmentBean.setPointOrLine(line.get(i));
            pointPoleBean.setEquip(1);

            poleFragmentBeansData.add(poleFragmentBean);
            bomBeanresult.add(pointPoleBean);

        }*/
        PoleAdapter2 poleAdapter = new PoleAdapter2(poleFragmentBeansData, getContext());
        pole_listView.setAdapter(poleAdapter);
        detailsBtnBack = (ImageButton) view.findViewById(R.id.detailsBtnBack);
        detailsBtnBack.setOnClickListener(this);
        detailsTvOne = (TextView) view.findViewById(R.id.detailsTvOne);
        detailsTvOne.setText("导出Excel");
        detailsTvOne.setOnClickListener(v -> {
            createProgressDialog();
            ThreadManager.ThreadPool threadPool = getThreadPool();
            threadPool.execute(mRunnable2);
        });
//        detailsTvOne.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                setMenu();
//            }
//        });
        detailsTvTwo = (TextView) view.findViewById(R.id.detailsTvTwo);
        detailsTvTwo.setOnClickListener(this);
        detailsBtnJc = (Button) view.findViewById(R.id.detailsBtnJc);
        detailsBtnJc.setOnClickListener(this);
        detailsBtnKcxx = (Button) view.findViewById(R.id.detailsBtnKcxx);
        detailsBtnKcxx.setOnClickListener(this);
        detailsBtnWlqd = (Button) view.findViewById(R.id.detailsBtnWlqd);
        detailsBtnWlqd.setOnClickListener(this);
        detailsBtnGdfa = (Button) view.findViewById(R.id.detailsBtnGdfa);
        detailsBtnGdfa.setOnClickListener(this);
        detailsBtnJc.setBackgroundResource(R.drawable.btn_shape_white);
        detailsBtnKcxx.setBackgroundResource(R.drawable.btn_shape);
        detailsBtnWlqd.setBackgroundResource(R.drawable.btn_shape_white);
        detailsBtnGdfa.setBackgroundResource(R.drawable.btn_shape_white);

        detailsBtnJc.setTextColor(Color.rgb(51, 51, 51));
        detailsBtnKcxx.setTextColor(Color.rgb(255, 255, 255));
        detailsBtnWlqd.setTextColor(Color.rgb(51, 51, 51));
        detailsBtnGdfa.setTextColor(Color.rgb(51, 51, 51));
        new BasisFragment().clickItem(this, detailsBtnBack, detailsBtnJc, detailsBtnKcxx, detailsBtnWlqd, detailsBtnGdfa);
    }

    private GaussKrugerProjection.Tuple get2000XY(String lat,String lng) {
        CoordinateTool.Location location = CoordinateTool.dbToWGS84(Double.parseDouble(lat), Double.parseDouble(lng));//转换获取GPS84坐标
        GaussKrugerProjection.Tuple tuple = GaussKrugerProjection.GetXY(location.getLat(), location.getLng(), 3, false);//获取大地2000的X,Y
        return tuple;
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                //若工作完成，取消动画，初始化界面
                if (mProgressDialog != null) {
                    mProgressDialog.cancel();
                }
            }
        }
    };
    /**
     * 在线项目更新点
     */
    private Runnable mRunnable1 = () -> {
        ExportUnit exportUnit = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            exportUnit = new ExportUnit(getContext(),Project.getId(), Project.getName());
            exportUnit.getKmlFile(pointsList,line);
            exportUnit.getZipsFileKml();
        }
        //需要耗时的工作
        Message msg = mHandler.obtainMessage();
        msg.what = 1;
        mHandler.sendMessage(msg);
    };
    /**
     * 在线项目更新点
     */
    private Runnable mRunnable2 = () -> {
        //需要耗时的工作
        export(1);
        Message msg = mHandler.obtainMessage();
        msg.what = 1;
        mHandler.sendMessage(msg);
    };

    /**
     * 设置头部下拉菜单栏
     */
    private void setMenu() {
        String[] abs = new String[]{"Excel", "Kmz"};
        PopupMenuPole popupMenu = new PopupMenuPole(getActivity(), abs);
        popupMenu.showLocation(R.id.detailsTvOne);
        popupMenu.setOnItemClickListener((item, str) -> {
            switch (str) {
                case "Excel": {
                    popupMenu.dismiss();
                    createProgressDialog();
                    ThreadManager.ThreadPool threadPool = getThreadPool();
                    threadPool.execute(mRunnable2);
                    break;
                }
                case "Kmz": {
                    popupMenu.dismiss();
                    createProgressDialog();
                    ThreadManager.ThreadPool threadPool = getThreadPool();
                    threadPool.execute(mRunnable1);
                    break;
                }
            }
        });
    }

    /**
     * 创建ProrgressDialog
     */
    private void createProgressDialog() {
        mProgressDialog = new ProgressDialog(getActivity());
        mProgressDialog.setMessage("加载数据中,请稍等...");
        mProgressDialog.show();
    }

    /**
     * 生成和导出Excel文件
     *
     * @param flag /
     */
    public void export(int flag) {
        Project Project = App.getInstances().getDaoSession().getProjectDao().queryBuilder().where(ProjectDao.Properties.Id.eq(ProjectDetailActivity.PROJECT_DETAILS_ID)).list().get(0);
        String excelName = Project.getName();
        String filePath = Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/bhne/";
        File files = new File(filePath);
        if (!files.exists()) {
            files.mkdirs();
        }
        String[] title = {"编号", "类别", "类型", "纬度", "经度", "高程", "备注"};
        String excelFileName = "/" + excelName + ".xls";
        String resultPath = files.getAbsolutePath() + excelFileName;
        ExcelUtil.initExcelPole(excelName, resultPath, title);
        File moudleFile = ExcelUtil.writeObjListToExcelToPel(bomBeanresult, resultPath, getContext());
        if (flag == 0) {
            if (moudleFile != null) {
                ToastUtils.showShort("已经保存到本地" + filePath);
            }
        } else {
            ShareUtils.shareFile(getActivity(), moudleFile);
        }
    }

    @Override
    public void onClick(View v) {

    }
}